package com.bodacn.keypoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentE extends Fragment implements View.OnClickListener {
    public static String TAG=FragmentE.class.getName();
    public static final int msgFocusBarcode = 1001;
    public static final int msgGetImg = 1002;
    public static final int msgShowImage =1003;
    public static final int msgGreenLight = 2001;
    public static final int msgRedLight = 2002;
    public static final int msgGrayLight = 2003;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_DETAIL = 9002;
    public static final int MSG_PROCRESULT=9004;

    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID;
    Button btn_find,btn_Query;
    ImageButton btn_editBarcode;
    ListView detailListView;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_StyleSort,txt_PO,txt_Color,txt_PackNo,txt_Size,txt_ReadyScan,txt_OwenScan,txt_Number,txt_TargetNum,txt_TodaySewNum;
    TextView tv_runState;
    EditText edt_barcode;
    CheckBox chk_Repeat;
    static Drawable drawable_gray,drawable_green,drawable_red;
    String curImageFileName ="",curStyleID="";
    ImageView imgv_StlyleImage;
    JSONArray detailJSON,queryJSON,procRstJSON;
    private ProgressDialog waitDialog = null;
    //主程序回调传参--------------------------------------------开始;
    private FragmentECallBack mFragmentECallBack;
    /*定义一个业务接口,主程序负责实现，所以需在主程序implements中加上这个接口的引用>>>>>切记<<<<<<
    该Fragment所在Activity需要实现该接口
    该Fragment将通过此接口与它所在的Activity交互*/
    public interface FragmentECallBack {
        // 里面传个值@param Map<String,Object>适应多种类型;
        void FragmentEWorkAndTransParams(Map<String, Object> Params);
    }
    //主程序回调传参--------------------------------------------结束;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity) context;
        if (!(activity instanceof FragmentECallBack)) {
            throw new IllegalStateException("MainActivity必须实现FragmentECallBack接口");
        }
        mFragmentECallBack=(FragmentECallBack) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mFragmentECallBack=null;
    }

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public FragmentE() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerE(new MainActivity.OnTransParamsListenerE() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(this.getClass().getName(),"LoginParam------------------>1");
                            System.out.println(mParams);
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir=mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(this.getClass().getName(),"LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (paramComm=="LightParam")
                        {
                            //Log.d(this.getClass().getName(),"LightParam------------------>1");
                            //传递登陆参数信息;
                            String ConColor=mParams.get("Color").toString();
                            //发消息置焦点
                            Message msg =new Message();
                            if (ConColor=="Green") msg.what = msgGreenLight;
                            if (ConColor=="Red") msg.what = msgRedLight;
                            if (ConColor=="Gray") msg.what = msgGrayLight;
                            fragmentHandler.removeMessages(msgGreenLight);
                            fragmentHandler.removeMessages(msgRedLight);
                            fragmentHandler.removeMessages(msgGrayLight);
                            fragmentHandler.sendMessage(msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }



    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                int msgId = msg.what;
                switch (msgId) {
                    case msgGreenLight:
                        tv_runState.setBackground(drawable_green);
                        tv_runState.refreshDrawableState();
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        break;
                    case msgRedLight:
                        tv_runState.setBackground(drawable_red);
                        tv_runState.refreshDrawableState();
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        break;
                    case msgGrayLight:
                        tv_runState.setBackground(drawable_gray);
                        tv_runState.refreshDrawableState();
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        break;

                    case msgGetImg:
                        //设置焦点
                        System.out.println(TAG+"获取图片-------------------------------1.Start");
                        if (curImageFileName.length()>0)
                            getImage(curStyleID,txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                        System.out.println(TAG+"获取图片-------------------------------1.End");
                        break;
                    case msgShowImage:
                        //判断本地是否有图片;
                        String imgfilepath = getActivity().getCacheDir().toString();
                        File file = new File(imgfilepath + "/" + curImageFileName);
                        //判断图片是否存在，如果不存在则从网络获取;
                        if (file.exists() == true) {
                            Log.d(TAG, "准备从本地取图片显示---------------");
                            //从本地取图片
                            Bitmap bitmap = getLoacalBitmap(imgfilepath + "/" + curImageFileName);
                            imgv_StlyleImage.setImageBitmap(bitmap);
                        }
                        break;
                    case msgFocusBarcode:
                        //任意消息来均置焦点
                        if (edt_barcode.isFocused()==false) setEditBarcodeFocus();
                        break;
                    case MSG_SCANBARCODE:
                        fillFormtext();
                        break;
                    case MSG_DETAIL:
                        //显示预排单;
                        final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
                        detailListView.setAdapter(detailListAdapter);
                        break;
                    case MSG_PROCRESULT:
                        String resultMsg = null;
                        try {
                            resultMsg = procRstJSON.optJSONObject(0).getString("PROCRESULT");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //提示提交完成，需确认;
                        // 创建对话框
                        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                .setTitle(getString(R.string.SystemHint)).setMessage(resultMsg)
                                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        hideBottomUIMenu();
                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                        break;
                    default:
                        break;
                }
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_e, container, false);
        initView(root);
        System.out.println(this.getClass().getName()+"_onCreateView");
        return root;
    }


    private void initView(View view) {
        detailListView=(ListView) view.findViewById(R.id.detailListView);
        detailListView.setFocusableInTouchMode(false);
        detailListView.setFocusable(false);
        btn_find=(Button)view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_Query=(Button)view.findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_editBarcode=(ImageButton)view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        imgv_StlyleImage = view.findViewById(R.id.imgv_StyleImage);
        imgv_StlyleImage.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //删除CacheDir文件
                deleteFilesByDirectory(getActivity().getCacheDir());
                curToast.setText("缓存文件已被清空!");
                curToast.show();
                return false;
            }
        });
        //运行状态;
        chk_Repeat=view.findViewById(R.id.chk_Repeat);
        chk_Repeat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //传消息给主界面;
                if (mFragmentECallBack!=null)
                {
                    fragmentParams.clear();
                    fragmentParams.put("ParamComm","Repeat");//命令;
                    if (isChecked==true) fragmentParams.put("ParamValue","T");//参数;
                    else fragmentParams.put("ParamValue","F");//参数;
                    mFragmentECallBack.FragmentEWorkAndTransParams(fragmentParams);
                } else Log.d("msg","mFragmentECallBack-----------空的咋办");
            }
        });
        tv_runState=view.findViewById(R.id.tv_runState);
        //状态背景颜色
        drawable_gray = getResources().getDrawable(R.drawable.round_gray_background);
        drawable_green = getResources().getDrawable(R.drawable.round_green_background);
        drawable_red = getResources().getDrawable(R.drawable.round_red_background);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        hideIM(v);
                        if (edt_barcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        }
                        //执行查询;
                        searchBarcodeData(edt_barcode.getText().toString(),txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString());
                        //未有焦点
                        if (edt_barcode.isFocused()==false){
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        } else edt_barcode.selectAll();
                    }

                }
                return false;
            }
        });
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        txt_HintInfo=view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=view.findViewById(R.id.txt_StyleNo);
        txt_PO=view.findViewById(R.id.txt_PO);
        txt_Color=view.findViewById(R.id.txt_Color);
        txt_PackNo=view.findViewById(R.id.txt_PackNo);
        txt_Size=view.findViewById(R.id.txt_Size);
        txt_ReadyScan=view.findViewById(R.id.txt_ReadyScan);
        txt_OwenScan=view.findViewById(R.id.txt_OwenScan);
        txt_Number=view.findViewById(R.id.txt_Number);
        txt_TargetNum=view.findViewById(R.id.txt_TargetNum);
        txt_TodaySewNum=view.findViewById(R.id.txt_TodaySewNum);
        txt_StyleSort=view.findViewById(R.id.txt_StyleSort);

        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);
        //提示框pd=new ProgressDialog(this);
        waitDialog = new ProgressDialog(getActivity());
        waitDialog.setTitle(getString(R.string.SystemHint));
    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }
    //刷新缸布列表;
    private void searchBarcodeData(String BarcodeParam,String OrderNoParam,String StyleNoParam)
    {
        playRingtone();
        //指示灯颜色为红色
        tv_runState.setBackground(drawable_red);
        //传消息给主界面;
        if (mFragmentECallBack!=null)
        {
            fragmentParams.clear();
            fragmentParams.put("ParamComm","CardNo");//命令;
            if (BarcodeParam.indexOf("#")==0) BarcodeParam=BarcodeParam.substring(1);
            if (BarcodeParam.length()>10)
                fragmentParams.put("ParamValue",BarcodeParam.substring(0,10));//参数;
            else
                fragmentParams.put("ParamValue",BarcodeParam);//参数;
            mFragmentECallBack.FragmentEWorkAndTransParams(fragmentParams);
        } else Log.d("msg","mFragmentECallBack-----------空的咋办");

        try {
            queryJSON=new JSONArray("[]");
            //清除界面显示内容;
            clearFormText();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_SewOnBarcode @Barcode='" + BarcodeParam + "',@OrderNo='" + OrderNoParam + "',@StyleNo='" + StyleNoParam
                + "',@OPERTYPE='SCANBARCODE',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //清除界面显示内容
    private void clearFormText(){
        /*

         */
    }
    //填充界面显示内容;
    private void fillFormtext(){
        if (queryJSON.length()>0)
        {
            try {
                if (queryJSON.getJSONObject(0).has("StyleID")==true) curStyleID=queryJSON.getJSONObject(0).getString("StyleID");
                if (queryJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(queryJSON.getJSONObject(0).getString("HintInfo"));
                if (queryJSON.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(queryJSON.getJSONObject(0).getString("OrderNo"));
                if (queryJSON.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(queryJSON.getJSONObject(0).getString("StyleNo"));
                if (queryJSON.getJSONObject(0).has("StyleSort")==true) txt_StyleSort.setText(queryJSON.getJSONObject(0).getString("StyleSort"));
                if (queryJSON.getJSONObject(0).has("PO")==true) txt_PO.setText(queryJSON.getJSONObject(0).getString("PO"));
                if (queryJSON.getJSONObject(0).has("Color")==true) txt_Color.setText(queryJSON.getJSONObject(0).getString("Color"));
                if (queryJSON.getJSONObject(0).has("PackNo")==true) txt_PackNo.setText(queryJSON.getJSONObject(0).getString("PackNo"));
                if (queryJSON.getJSONObject(0).has("Size")==true) txt_Size.setText(queryJSON.getJSONObject(0).getString("Size"));
                if (queryJSON.getJSONObject(0).has("ReadyScan")==true) txt_ReadyScan.setText(queryJSON.getJSONObject(0).getString("ReadyScan"));
                if (queryJSON.getJSONObject(0).has("OwenScan")==true) txt_OwenScan.setText(queryJSON.getJSONObject(0).getString("OwenScan"));
                if (queryJSON.getJSONObject(0).has("Number")==true) txt_Number.setText(queryJSON.getJSONObject(0).getString("Number"));
                if (queryJSON.getJSONObject(0).has("TargetNum")==true) txt_TargetNum.setText(queryJSON.getJSONObject(0).getString("TargetNum"));
                if (queryJSON.getJSONObject(0).has("TodaySewNum")==true) txt_TodaySewNum.setText(queryJSON.getJSONObject(0).getString("TodaySewNum"));
                if (queryJSON.getJSONObject(0).has("ErrInfo")==true)
                {
                    MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(),R.raw.warn);
                    mediaPlayer.start();
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(getString(R.string.SystemHint)).setMessage(queryJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                if (queryJSON.getJSONObject(0).has("ImgFileName") == true){
                    curImageFileName =queryJSON.getJSONObject(0).getString("ImgFileName");
                    //判断本地是否有图片;
                    String imgfilepath = getActivity().getCacheDir().toString();
                    File file = new File(imgfilepath + "/" + curImageFileName);
                    System.out.println("图片文件路径:" + imgfilepath + "/" + curImageFileName);
                    //判断图片是否存在，如果不存在则从网络获取;
                    if (file.exists() == true) {
                        Log.d(TAG, "准备从本地取图片显示---------------");
                        //从本地取图片
                        Bitmap bitmap = getLoacalBitmap(imgfilepath + "/" + curImageFileName);
                        imgv_StlyleImage.setImageBitmap(bitmap);
                    } else {
                        Log.d(TAG, "发消息从网络获取图片---------------");
                        Drawable drawable = getResources().getDrawable(R.mipmap.err404);
                        BitmapDrawable errBitDraw = (BitmapDrawable) drawable;
                        imgv_StlyleImage.setImageBitmap(errBitDraw.getBitmap());
                        //发前消息，获取图片;
                        Message msg = new Message();
                        msg.what = msgGetImg;
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        System.out.println("fillFormtext----------edt_barcode置焦点");
        setEditBarcodeFocus();
    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }
    @Override
    public void onStart() {
        super.onStart();
        setEditBarcodeFocus();
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_find:
                if (edt_barcode.getText().length()==0) {
                    curToast.setText(getString(R.string.PleaseInputBarcode));
                    curToast.show();
                } else searchBarcodeData(edt_barcode.getText().toString(),txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString());
                break;
            case R.id.btn_Query:
                refreshDetailData("");
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;

            default:
                break;
        }
    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    //刷新今日扫描明细;
    private void refreshDetailData(String paramDate)
    {
        try {
            detailJSON=new JSONArray("[]");
            //显示到orderListGrid中;
            final DetailListAdapter detailListAdapter=new DetailListAdapter(getActivity());
            detailListView.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_SewOnGetDetail @DepartmentNo='" + curDepartNo  + "',@WorkDate='"+paramDate
                + "',@OPERTYPE='DETAIL',@UserNo='"+curLoginUserNo+ "',@CPUID='" + CPUID +"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = ToolUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OPERTYPE") == true) {
                            System.out.println("OPERTYPE:" + jsonArray.optJSONObject(0).getString("OPERTYPE"));
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("SCANBARCODE")) {
                                queryJSON = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_SCANBARCODE;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }

                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("DETAIL"))
                            {
                                detailJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_DETAIL;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);

                            }
                        }
                        if (jsonArray.optJSONObject(0).has("PROCRESULT") == true) {
                            procRstJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_PROCRESULT;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();
    }

    //刷新缸布列表;
    private void getImage(final String paramStyleID,final String paramStyleNo,final String paramStyleSort)
    {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    ResultSet re = ToolUtil.OpenSQL("Exec KeyPoint_GetStylePNG @StyleID='" + paramStyleID + "',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort + "'");
                    if (re != null) {
                        re.next();
                        //使用Blob对象接收数据库里的图片
                        if (re.findColumn("ImgResult") > -1) {
                            String ImgResult = re.getString("ImgResult");
                            if (ImgResult.equals("OK")) {
                                java.sql.Blob imgBlob = re.getBlob("ImgFile");
                                //获取Blob对象的二进制流;
                                InputStream imgInS = imgBlob.getBinaryStream();
                                //加载一个网络图片
                                Bitmap bitmap = BitmapFactory.decodeStream(imgInS);
                                //保存图片;
                                saveBitmap(bitmap, curImageFileName);
                                //发消息显示图片;
                                Message msg = new Message();
                                msg.what = msgShowImage;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                        }
                    }
                    re.getStatement().getConnection().close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(run).start();
    }


    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    /**
     * @param @param  url 本地路径
     * @param @return
     * @return Bitmap
     * @throws
     * @Title: getLoacalBitmap
     * @Description: 加载本地图片
     */
    public Bitmap getLoacalBitmap(String url) {
        if (url != null) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(url);
                return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fis = null;
                }
            }
        } else {
            return null;
        }
    }


    /**
     * 保存文件
     */
    public void saveBitmap(Bitmap bm, String fileName) {
        //获取MainActivity
        MainActivity activity = (MainActivity) getActivity();
        //String imgfilepath=activity.SaveFilePath+activity.SaveIMGFolder;
        String imgfilepath = activity.getCacheDir().toString();
        Log.d("saveBitmap", "imgfilepath:" + imgfilepath);
        File f = new File(imgfilepath, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            if (fileName.toUpperCase().indexOf("PNG") > 0)
                bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            if ((fileName.toUpperCase().indexOf("JPG") > 0) || (fileName.toUpperCase().indexOf("JPEG") > 0))
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i("saveBitmap", "已经保存成功");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_e_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(38)));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (detailJSON.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = detailJSON.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.txt_item_hoursection);// 显示文字
                if (detailJSON.optJSONObject(position).has("HourSection")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("HourSection").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_orderno);// 显示文字
                if (detailJSON.optJSONObject(position).has("OrderNo")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("OrderNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_styleno);// 显示文字
                if (detailJSON.optJSONObject(position).has("StyleNo")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("StyleNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_stylesort);// 显示文字
                if (detailJSON.optJSONObject(position).has("StyleSort")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("StyleSort").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_color);// 显示文字
                if (detailJSON.optJSONObject(position).has("Color")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Color").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_size);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Size").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_number);// 显示文字
                if (detailJSON.optJSONObject(position).has("Number")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Number").toString());
                tv.setTextColor(color);


            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }
    }


}
